<?php

namespace app\admin\model\express;

use think\Model;


class Batch extends Model
{


    // 表名
    protected $name = 'express_batch';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'state_text'
    ];


    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1'), '2' => __('State 2'), '3' => __('State 3'), '4' => __('State 4'), '5' => __('State 5'), '6' => __('State 6')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    //获取批次编号
    public function getBatchNo()
    {
        $date = date("Ymd");
        $info = $this->whereTime('createtime', 'today')->field(["id", "batch_no"])->order("id", "desc")->find();
        if (empty($info)) {
            $batch_no = $date . "-1";
        } else {
            $current_batch_no = $info['batch_no'];
            if (empty($current_batch_no)) {
                $batch_no = $date . "-1";
            } else {
                $ar = explode('-', $current_batch_no);
                $no = (int)($ar[1] ?? 0);
                $no += 1;
                $batch_no = $date . "-" . $no;
            }
        }
        return $batch_no;
    }


    public function track()
    {
        return $this->belongsTo(Track::class, 'state', 'id', [], 'LEFT')->setEagerlyType(0);
    }

}
